﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Luminji.Core.Web.Safe
{
    public class SessionHijackingDefender
    {
        public static void Defend(System.Web.UI.Page page)
        {
            ChangeSessionID(page);
        }

        private static void ChangeSessionID(System.Web.UI.Page page)
        {
            SessionIDManager m = new SessionIDManager();
            m.RemoveSessionID(HttpContext.Current);
            HttpApplication ctx = HttpContext.Current.ApplicationInstance;
            HttpModuleCollection mods = ctx.Modules;
            SessionStateModule sessionStateModule
                = (SessionStateModule)mods.Get("Session");
            MethodInfo createSessionId = sessionStateModule.GetType().GetMethod(
                "CreateSessionId", BindingFlags.Instance | BindingFlags.NonPublic);
            MethodInfo initStateStoreItem = sessionStateModule.GetType().GetMethod(
                "InitStateStoreItem", BindingFlags.Instance | BindingFlags.NonPublic);
            createSessionId.Invoke(sessionStateModule, null);
            SessionStateUtility.RemoveHttpSessionStateFromContext(HttpContext.Current);
            initStateStoreItem.Invoke(sessionStateModule, new object[] { true });

            FieldInfo sessioninfo = page.GetType().BaseType.BaseType.GetField(
                "_session", BindingFlags.NonPublic | BindingFlags.Instance);
            sessioninfo.SetValue(page, HttpContext.Current.Session);
        }
    }
}
